/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package samoloty.controler;

import Utils.MainValidator;
import Utils.ScreensOrder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import samoloty.model.IDataModel;
import samoloty.view.ConfirmPanel;
import samoloty.view.ContentPanel;

import samoloty.view.MainWindow;
import samoloty.view.PlotPanel;

/**
 *
 * @author borysfan
 */
public class Controler {

    private MainWindow window = new MainWindow();
    private StartPanelControler startPanelControler;
    private MainPanelControler mainPanelControler;
    private SecondPanelControler secondPanelControler;
    private ThirdPanelControler thirdPanelControler;
    private FlightPanelControler flightPanelControler;
    private DowPanelControler dowPanelControler;
    private FuelPanelControler fuelPanelControler;
    private PaxPanelControler paxPanelControler;
    private HoldsPanelControler holdsPanelControler;
    private DisplayPanelControler displayPanelControler;
    private HelpPanelControler helpPanelControler;
    private ConfirmPanel confirmPanel;
    private Controler instance = this;
    private PlotPanelControler plotPanelControler;
    private InfoPanelControler infoPanelControler;
    private SiPanelControler siPanelControler;
    private AcRegPanelControler acRegPanelControler;
    private IDataModel dataModel;
    private String activeWindow;
    private ScreensOrder order;
    private int currentPanelId = -1;
    private String vacreg;
    private MainValidator mainValidator;

    public void startApp() {
        initWindow();
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                window.setVisible(true);
            }
        });
    }

    private void initWindow() {
        confirmPanel = new ConfirmPanel();
        confirmPanel.setControler(this);
        mainValidator = MainValidator.getInstance(this);
        window.setPrintBtnListener(new PrintListener());
        window.setFlightBtnListener(new FlightAction());
        window.setDowBtnListener(new DowAction());
        window.setFuelBtnListener(new FuelAction());
        window.setPaxBtnListener(new PaxAction());
        window.setHoldBtnListener(new HoldAction());
        window.setDisplayBtnListener(new DisplayAction());
        window.setExitBtnListener(new ExitAction());

        this.enableShortCuts(false);
        this.enableExitShortcut(true);

        window.setResetBtnListener(new ResetAction());
        window.setHelpBtnListner(new HelpAction());
        window.setSiBtnListener(new SiAction());
        window.setSaveBtnListener(new SaveAction());
        window.setKeyListener(new EnterListener());

        mainPanelControler = new MainPanelControler(this);
        startPanelControler = new StartPanelControler(this);
        secondPanelControler = new SecondPanelControler(this);
        thirdPanelControler = new ThirdPanelControler(this);
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {

                infoPanelControler = new InfoPanelControler(instance, dataModel);
                flightPanelControler = new FlightPanelControler(instance, dataModel);
                dowPanelControler = new DowPanelControler(instance, dataModel);
                fuelPanelControler = new FuelPanelControler(instance, dataModel);
                paxPanelControler = new PaxPanelControler(instance, dataModel);
                holdsPanelControler = new HoldsPanelControler(instance, dataModel);
                displayPanelControler = new DisplayPanelControler(instance, dataModel);
                helpPanelControler = new HelpPanelControler(instance);
                plotPanelControler = new PlotPanelControler(instance, dataModel);
                siPanelControler = new SiPanelControler(instance, dataModel);
                acRegPanelControler = new AcRegPanelControler(instance);
                reset();
            }
        });

        setStartPanel();
        order = ScreensOrder.getInstance();
        order.setControler(this);

    }

    public void initTray() {
    }

    public void reset() {

        siPanelControler.reset();
        flightPanelControler.reset();
        fuelPanelControler.reset();
        holdsPanelControler.reset();
        paxPanelControler.reset();
        dowPanelControler.reset();
        displayPanelControler.reset();
        infoPanelControler.reset();
        window.setTitleBar("");
        mainValidator.validate();
    }

    public void setDataModel(IDataModel data) {
        dataModel = data;
        dowPanelControler.setDataModel(dataModel);
        holdsPanelControler.setDataModel(dataModel);
        paxPanelControler.setDataModel(dataModel);
        fuelPanelControler.setDataModel(dataModel);
        plotPanelControler.setDataModel(dataModel);
        infoPanelControler.setDataModel(dataModel);
        siPanelControler.setDataModel(dataModel);
        infoPanelControler.update();
        //initWindow();
    }

    public void setTitleBar(String s) {
        window.setTitleBar(s);
        System.err.println(s);
    }

    public String getTitleBar() {
        return window.getTitleBar();
    }

    public void setStartPanel() {
        currentPanelId = startPanelControler.getPanel().getIdentity();
        window.setPanel(startPanelControler.getPanel());
        window.repaint();
        window.unvisibleLeftCorenerTitle();
        window.setButtonsInActive();
        this.getView().setFocusableComponents(false);
        startPanelControler.setUpWindow();

        activeWindow = startPanelControler.getPanel().toString().split("samoloty.view.")[1].split("\\[")[0];

    }

    public void setMainPanel() {
        currentPanelId = mainPanelControler.getPanel().getIdentity();
        window.setPanel(mainPanelControler.getPanel());
        mainPanelControler.setUpWindow();
        mainPanelControler.getPanel().setFirstFocused();
        window.repaint();
        window.visibleLeftCorenerTitle();
        activeWindow = mainPanelControler.getPanel().toString().split("samoloty.view.")[1].split("\\[")[0];
    }

    public void setDefaultPanel() {
        currentPanelId = this.getControler().getPanel().getIdentity();
        window.setLeftPanelVisible(true);
        window.setRightPanelVisible(true);
        window.setPanel(this.getControler().getPanel());
        this.getControler().firstFocused();
        window.repaint();

        window.visibleLeftCorenerTitle();
        mainValidator.validate();
    }

    public void setEmptyPanel() {
        ContentPanel tmp = new ContentPanel();
        currentPanelId = tmp.getIdentity();
        window.setPanel(tmp);
        window.repaint();
        window.visibleLeftCorenerTitle();
    }

    public void setAcRegPanel(ArrayList<IDataModel> models) {
        currentPanelId = acRegPanelControler.getPanel().getIdentity();
        acRegPanelControler.setDataModels(models);
        window.setPanel(acRegPanelControler.getPanel());
        acRegPanelControler.getPanel().requestFocus();
        acRegPanelControler.getPanel().setFirstFocused();
        acRegPanelControler.setUpWindow();
        window.repaint();
        window.visibleLeftCorenerTitle();
        window.setButtonsInActive();
        activeWindow = acRegPanelControler.getPanel().toString().split("samoloty.view.")[1].split("\\[")[0];
        this.enableShortCuts(true);

    }

    public void setFlightPanel() {
        currentPanelId = flightPanelControler.getPanel().getIdentity();
        window.setPanel(flightPanelControler.getPanel());
        flightPanelControler.setUpWindow();
        window.repaint();
        window.visibleLeftCorenerTitle();
        window.setButtonsInActive();
        activeWindow = flightPanelControler.getPanel().toString().split("samoloty.view.")[1].split("\\[")[0];
        this.enableShortCuts(true);
        mainValidator.validate();
    }

    public void setDowPanel() {
        currentPanelId = dowPanelControler.getPanel().getIdentity();
        window.setPanel(dowPanelControler.getPanel());
        dowPanelControler.setUpWindow();
        dowPanelControler.firstFocused();

        window.visibleLeftCorenerTitle();
        window.repaint();
        window.setButtonsInActive();
        activeWindow = dowPanelControler.getPanel().toString().split("samoloty.view.")[1].split("\\[")[0];
        this.enableShortCuts(true);
        mainValidator.validate();
    }

    public void setFuelPanel() {
        currentPanelId = fuelPanelControler.getPanel().getIdentity();
        window.setPanel(fuelPanelControler.getPanel());
        fuelPanelControler.setUpWindow();
        window.repaint();
        window.visibleLeftCorenerTitle();
        window.setButtonsInActive();
        activeWindow = fuelPanelControler.getPanel().toString().split("samoloty.view.")[1].split("\\[")[0];
        this.enableShortCuts(false);
        this.enableHelpShortcut(true);
        mainValidator.validate();
    }

    public void setPaxPanel() {
        currentPanelId = paxPanelControler.getPanel().getIdentity();
        window.setPanel(paxPanelControler.getPanel());
        paxPanelControler.setUpWindow();
        window.repaint();
        window.visibleLeftCorenerTitle();
        window.setButtonsInActive();
        activeWindow = paxPanelControler.getPanel().toString().split("samoloty.view.")[1].split("\\[")[0];
        this.enableShortCuts(false);
        this.enableHelpShortcut(true);
        mainValidator.validate();
    }

    public void setHoldPanel() {
        currentPanelId = holdsPanelControler.getPanel().getIdentity();
        window.setPanel(holdsPanelControler.getPanel());
        holdsPanelControler.setUpWindow();
        window.repaint();
        window.visibleLeftCorenerTitle();
        window.setButtonsInActive();
        activeWindow = holdsPanelControler.getPanel().toString().split("samoloty.view.")[1].split("\\[")[0];
        this.enableShortCuts(true);
        mainValidator.validate();
    }

    public void setDisplayPanel() {
        currentPanelId = displayPanelControler.getPanel().getIdentity();
        window.setPanel(displayPanelControler.getPanel());
        displayPanelControler.setUpWindow();
        displayPanelControler.update();
        window.repaint();
        window.visibleLeftCorenerTitle();
        window.setButtonsInActive();
        activeWindow = displayPanelControler.getPanel().toString().split("samoloty.view.")[1].split("\\[")[0];
        mainValidator.validate();
    }

    public void setHelpPanel() {
        currentPanelId = helpPanelControler.getPanel().getIdentity();
        window.setPanel(helpPanelControler.getPanel());
        helpPanelControler.setUpWindow();
        window.repaint();
        window.visibleLeftCorenerTitle();
        window.setButtonsInActive();
        activeWindow = helpPanelControler.getPanel().toString().split("samoloty.view.")[1].split("\\[")[0];
        mainValidator.validate();
    }

    public void setSiPanel() {
        currentPanelId = siPanelControler.getPanel().getIdentity();
        window.setPanel(siPanelControler.getPanel());
        siPanelControler.setUpWindow();
        siPanelControler.update();
        window.repaint();
        window.visibleLeftCorenerTitle();
        window.setButtonsInActive();
        activeWindow = siPanelControler.getPanel().toString().split("samoloty.view.")[1].split("\\[")[0];
        mainValidator.validate();
    }

    public int getCurrentPanelIdentity() {
        return currentPanelId;
    }

    /*wszystkie sety*/
    public void setView(JFrame view) {
        window = (MainWindow) view;
    }

    public MainWindow getView() {
        return window;
    }

    public FlightPanelControler getFlightControler() {
        return flightPanelControler;
    }

    public PlotPanel getPlotPanel() {
        return plotPanelControler.getPanel();
    }

    public void setSecondPanel() {
        window.setPanel(secondPanelControler.getPanel());
        secondPanelControler.setUpWindow();
        window.repaint();
    }

    public void setThirdPanel() {
        window.setPanel(secondPanelControler.getPanel());
        secondPanelControler.setUpWindow();
        window.repaint();
    }

    public InfoPanelControler getInfoPanelControler() {
        return infoPanelControler;
    }

    public IDataModel getDataModel() {
        return dataModel;
    }

    public void resetProgram() {

        reset();
        // setStartPanel();
        setMainPanel();
        window.setButtonsActive();
        window.setExitVisible(true);
        window.setHelpVisible(true);
        window.setResetVisible(true);
    }

    public void exitProgram() {
        window.dispose();
    }

    public void set_vacreg(String text) {
        this.vacreg = text;
    }

    public String get_vacreg() {
        return vacreg;
    }

    /*Wszystkie ActionListenery*/
    private class FlightAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            setFlightPanel();
        }
    }

    private class DowAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {

            setDowPanel();
        }
    }

    private class FuelAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            setFuelPanel();
        }
    }

    private class PaxAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            setPaxPanel();
        }
    }

    private class HoldAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {

            setHoldPanel();
        }
    }

    private class SiAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            setSiPanel();
        }
    }

    private class DisplayAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            setDisplayPanel();
        }
    }

    public void setExitPanel() {
        instance.setEmptyPanel();
        window.setPanel(confirmPanel);
        confirmPanel.setExitAction();
        instance.getView().setRightPanelVisible(false);
        instance.getView().setLeftPanelVisible(false);
        window.repaint();
    }

    public void setResetPanel() {
        instance.setEmptyPanel();
        window.setPanel(confirmPanel);
        confirmPanel.setResetAction();
        instance.getView().setRightPanelVisible(false);
        instance.getView().setLeftPanelVisible(false);
        window.repaint();
    }

    private class ExitAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            setExitPanel();
            instance.getView().setRightPanelVisible(false);
        }
    }

    private class ResetAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            setResetPanel();
            instance.getView().setRightPanelVisible(false);
        }
    }

    private class HelpAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            setHelpPanel();
        }
    }

    private class PrintListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            java.awt.EventQueue.invokeLater(new Runnable() {

                public void run() {
                    displayPanelControler.printPage();
                }
            });

        }
    }

    private class SaveAction implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            java.awt.EventQueue.invokeLater(new Runnable() {

                public void run() {
                    JFileChooser fileChooser = new JFileChooser();
                    File dir = fileChooser.getCurrentDirectory();
                    fileChooser.setSelectedFile(new File(dir.getPath() + "\\loadsheet.txt"));
                    fileChooser.setApproveButtonText("Save");
                    int retv = fileChooser.showOpenDialog(window);
                    if (retv == JFileChooser.APPROVE_OPTION) {
                        File file = fileChooser.getSelectedFile();
                        if (file.exists() == true) {

                            JOptionPane pane = new JOptionPane("File already exist. Do you want to overwrite file?", JOptionPane.WARNING_MESSAGE, JOptionPane.YES_NO_OPTION);
                            JDialog dialog = pane.createDialog(window, "Warning");
                            dialog.show();
                            Object selectedValue = pane.getValue();
                            if (selectedValue instanceof Integer) {
                                int value = (Integer) selectedValue;
                                if (value == 0) {
                                    file.delete();
                                } else {
                                    this.run();
                                }
                            }
                        }
                        try {
                            FileOutputStream out = new FileOutputStream(file);

                            String content = displayPanelControler.update();
                            String[] splited = content.split(content, '\n');
                            String newline = System.getProperty("line.separator");
                            if (splited != null) {
                                for (int i = 0; i < splited.length; i++) {
                                    out.write(splited[i].getBytes());
                                    out.write(newline.getBytes());
                                }
                            }
                            out.close();
                        } catch (IOException ex) {
                            JOptionPane.showMessageDialog(window, "There was an error when saving file!");

                        }

                    }
                }
            });
        }
    }

    private class EnterListener implements KeyListener {

        public void keyTyped(KeyEvent e) {
        }

        public void keyPressed(KeyEvent e) {
            System.out.println(e.getKeyCode());
        }

        public void keyReleased(KeyEvent e) {
        }
    }

    /*gettery dla poszczegolnych kontrolerow. Potrzebne w InfoSubPanel*/
    public FlightPanelControler getFlightPanelControler() {
        return flightPanelControler;
    }

    public DowPanelControler getDowPanelControler() {
        return dowPanelControler;
    }

    public FuelPanelControler getFuelPanelControler() {
        return fuelPanelControler;
    }

    public PaxPanelControler getPaxPanelControler() {
        return paxPanelControler;
    }

    public HoldsPanelControler getHoldsPanelControler() {
        return holdsPanelControler;
    }

    public PlotPanelControler getPlotPanelControler() {
        return plotPanelControler;
    }

    public SiPanelControler getSiPanelControler() {
        return siPanelControler;
    }

    public ScreensOrder getOrder() {
        return order;
    }

    public double compute_vttlholdsw() {
        return infoPanelControler.compute_vttlholdsw();
    }

    public MyControler getControler() {
        String controler = activeWindow.substring(0, 1).toLowerCase() + activeWindow.substring(1);
        if (controler.equals("startPanel")) {
            window.setLeftPanelVisible(false);
            window.setRightPanelVisible(false);
            window.setExitVisible(true);
            return startPanelControler;
        } else if (controler.equals("acRegPanel")) {
            window.setLeftPanelVisible(false);
            window.setRightPanelVisible(false);
            window.setExitVisible(true);
            window.setResetVisible(true);
            window.setHelpVisible(true);
            return acRegPanelControler;
        } else if (controler.equals("mainPanel")) {
            window.setLeftPanelVisible(false);
            window.setRightPanelVisible(false);
            window.setExitVisible(true);
            window.setResetVisible(true);
            window.setHelpVisible(true);
            return mainPanelControler;
        } else if (controler.equals("flightPanel")) {
            return flightPanelControler;
        } else if (controler.equals("dowPanel")) {
            return dowPanelControler;
        } else if (controler.equals("dowPanel")) {
            return dowPanelControler;
        } else if (controler.equals("fuelPanel")) {
            return fuelPanelControler;
        } else if (controler.equals("paxPanel")) {
            return paxPanelControler;
        } else if (controler.equals("holdsPanel")) {
            return holdsPanelControler;
        } else if (controler.equals("siPanel")) {
            return siPanelControler;
        } else if (controler.equals("displayPanel")) {
            return displayPanelControler;
        } else if (controler.equals("helpPanel")) {
            return helpPanelControler;
        } else {
            return null;
        }
    }

    public void enableShortCuts(boolean value) {
        enableExitShortcut(value);
        enableHelpShortcut(value);
        enableResetShortcut(value);
        enableF1F2Shortcut(value);
    }

    public void enableExitShortcut(final boolean enable) {
        InputMap inputMap = window.getRightPanel().getInputMap();
        ActionMap actionMap = window.getRightPanel().getActionMap();
        KeyStroke exitKey = KeyStroke.getKeyStroke(KeyEvent.VK_E, KeyEvent.CTRL_MASK);
        KeyStroke exitKey2 = KeyStroke.getKeyStroke("ESCAPE");
        inputMap.put(exitKey, "exitK");
        inputMap.put(exitKey2, "exitK");
        Action exitAA = new AbstractAction() {

            public void actionPerformed(ActionEvent e) {
                if (enable) {
                    setExitPanel();
                }
            }
        };
        actionMap.put("exitK", exitAA);
    }

    public void enableHelpShortcut(final boolean enable) {
        InputMap inputMap = window.getRightPanel().getInputMap();
        ActionMap actionMap = window.getRightPanel().getActionMap();
        KeyStroke helpKey = KeyStroke.getKeyStroke(KeyEvent.VK_H, KeyEvent.CTRL_MASK);
        inputMap.put(helpKey, "helpK");
        Action helpAA = new AbstractAction() {

            public void actionPerformed(ActionEvent e) {
                if (enable) {
                    setHelpPanel();
                }
            }
        };
        actionMap.put("helpK", helpAA);
    }

    public void enableResetShortcut(final boolean enable) {
        InputMap inputMap = window.getRightPanel().getInputMap();
        ActionMap actionMap = window.getRightPanel().getActionMap();
        KeyStroke resetKey = KeyStroke.getKeyStroke(KeyEvent.VK_R, KeyEvent.CTRL_MASK);
        inputMap.put(resetKey, "resetK");
        Action resetAA = new AbstractAction() {

            public void actionPerformed(ActionEvent e) {
                if (enable) {
                    setResetPanel();
                }
            }
        };
        actionMap.put("resetK", resetAA);
    }

    public void enableF1F2Shortcut(final boolean enable) {
        InputMap inputMap = window.getCenterPanel().getInputMap();
        ActionMap actionMap = window.getCenterPanel().getActionMap();
        KeyStroke f1Key = KeyStroke.getKeyStroke("F1");
        KeyStroke f2Key = KeyStroke.getKeyStroke("F2");
        inputMap.put(f1Key, "f1K");
        inputMap.put(f2Key, "f2K");
        Action f1AA = new AbstractAction() {

            public void actionPerformed(ActionEvent e) {
                if (enable) {
                    ScreensOrder order = ScreensOrder.getInstance();
                    order.prevScreen();
                }
            }
        };
        Action f2AA = new AbstractAction() {

            public void actionPerformed(ActionEvent e) {
                if (enable) {
                    ScreensOrder order = ScreensOrder.getInstance();
                    order.nextScreen();
                }
            }
        };
        actionMap.put("f1K", f1AA);
        actionMap.put("f2K", f2AA);
    }

    public MainValidator getMainValidator() {
        return this.mainValidator;
    }
}
